package nc.pub.yf.kit;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import nc.bs.framework.common.RuntimeEnv;
import nc.bs.framework.server.ServerConfiguration;
import nc.bs.logging.Logger;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

/**
 * 文件工具类,<br>
 * 用于记录调用接口输入输出<br>
 * 
 * @author xiaoj<br>
 *         2015-3-22 上午11:03:50
 */
public class FileKit {
	private static ExecutorService pool = Executors.newFixedThreadPool(4 + 4 * Runtime.getRuntime().availableProcessors());
	private static FileKit fk = new FileKit();
	/**
	 * 写日志任务
	 * 
	 * @param filepath
	 *            完整的日志文件路径
	 * @param loglist
	 *            日志
	 */
	private static void addTask(String filepath, List<String> loglist) {
		PoolWorker work = fk.new PoolWorker(filepath, loglist);
		pool.execute(work);
	}

	/**
	 * 写Exception堆栈日志
	 * 
	 * @param e
	 * @param code
	 */
	public static void addTask(Exception e, String code) {
		ArrayList<String> loglist = new ArrayList<String>();
		loglist.add(getErrMsg(e));
		addTask(loglist, code, "");
	}

	/**
	 * 写日志任务
	 * 
	 * @param loglist
	 *            日志
	 * @param code
	 *            接口编码
	 */
	public static void addTask(List<String> loglist, String code) {
		addTask(loglist, code, "");
	}

	/**
	 * 写日志任务
	 * 
	 * @param loglist
	 *            日志
	 * @param code
	 *            接口编码
	 * @param filestart
	 *            文件名开头
	 */
	public static void addTask(List<String> loglist, String code, String filestart) {
		try {
			String nchome = RuntimeEnv.getInstance().getNCHome();
			nchome = nchome.replace("\\", "/");
			if (!nchome.endsWith("/"))
				nchome += "/";
			String rq = new UFDate(System.currentTimeMillis()).toString().replace("-", "").substring(0, 8);
			String servername = ServerConfiguration.getServerConfiguration().getServerName();
			String path = "nclogs/cec/" + code + "/" + rq+filestart + ".txt";
			//add by ouyangzhb 2017-08-17 删除两天前的日志
			deleteFile(nchome,code);
			FileKit.addTask(nchome + path, loglist);
		} catch (Exception ex) {
			ex.printStackTrace();
			Logger.error(ex);
		}
	}

	private class PoolWorker extends Thread {
		String filepath;
		List<String> str;

		public PoolWorker(String filepath, List<String> str) {
			this.filepath = filepath.replace("\\", "/");
			this.str = str;
		}

		@Override
		public void run() {
			try {
				StringBuilder sb = new StringBuilder();
				for (String s : str) {
					sb.append(s).append("\r\n");
				}
				FileWriter writer;
				new File(filepath.substring(0, filepath.lastIndexOf("/"))).mkdirs();
				File f = new File(filepath);
				f.createNewFile();
				writer = new FileWriter(f,true);
				writer.write(sb.toString());

				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
				Logger.error(e);
			}

		}
	}

	/**
	 * 返回Exception的堆栈信息
	 * 
	 * @param e
	 * @return
	 */
	public static String getErrMsg(Exception e) {
		return org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
	}

	/**
	 * 返回Exception的堆栈信息并放到list中
	 * 
	 * @param e
	 * @param list
	 * @return
	 */
	public static String getErrMsg(Exception e, List<String> list) {
		String msg = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
		list.add(msg);
		return msg;
	}
	
	/**
	 * 删除两天前的日志；
	 * @author ouyangzhb
	 * @date 2017-8-17 下午2:12:09
	 */
	public static void deleteFile(String nchome,String filecode) {
		String trq = new UFDate(System.currentTimeMillis()).toString().replace("-", "").substring(0, 8);
		String yrq = new UFDate(System.currentTimeMillis()).getDateBefore(1).toString().replace("-", "").substring(0, 8);
		String yyrq = new UFDate(System.currentTimeMillis()).getDateBefore(2).toString().replace("-", "").substring(0, 8);
		String path = nchome + "nclogs/cec/" + filecode;
		File fdir = new File(path);
		File[] file = fdir.listFiles();
		if (file != null && file.length > 0) {
			for (int j = 0; j < file.length; j++) {
				if (!(file[j].getPath().contains(trq) || file[j].getPath().contains(yrq)|| file[j].getPath().contains(yyrq))) {
//					delAll(file[j]);
				}
			}
		}
	}
	
	/**
	 * 递归删除目录下的文件
	 * @author ouyangzhb
	 * @date 2017-8-17 下午2:12:32
	 * @param f
	 */
	public static void delAll(File f) {
		if (!f.exists())// 文件夹不存在不存在
			ExceptionUtils.wrappBusinessException("指定目录不存在:" + f.getName());
		boolean rslt = true;// 保存中间结果
		if (!(rslt = f.delete())) {// 先尝试直接删除
			// 若文件夹非空。枚举、递归删除里面内容
			File subs[] = f.listFiles();
			for (int i = 0; i <= subs.length - 1; i++) {
				if (subs[i].isDirectory())
					delAll(subs[i]);// 递归删除子文件夹内容
				rslt = subs[i].delete();// 删除子文件夹本身
			}
			rslt = f.delete();
		}// 删除此文件夹本身
		return;
	}
}
